package com.cictec.middleware.gps.engine.position.handler.alarms;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.PropertiesUtils;
import com.cictec.middleware.core.entity.DeparterSchedule;
import com.cictec.middleware.feign.distribute.SendPlatformMessageToTerminalService;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.exception.BusPositionWarnHandlerException;
import com.cictec.middleware.gps.engine.position.handler.BusPositionAlarmsHandler;
import com.cictec.middleware.gps.service.BusLineService;
import com.cictec.middleware.gps.service.ScheduleService;

/**
 * 下一趟发车时刻预警提醒报警
 * 
 * @author ql
 * @date 2017年9月26日
 */
@Component
public class NextDepartureAlertWarnHandler implements WarnHandler {

	private static Logger logger = LoggerFactory.getLogger(BusPositionAlarmsHandler.class);

	@Autowired
	private ScheduleService scheduleService;
	@Autowired
	private BusLineService busLineService;
	@Autowired
	private SendPlatformMessageToTerminalService sendPlatformMessageToTerminalService;

	private Map<String, NextDepartureEntity> nextDepartureAlertMap = new HashMap<String, NextDepartureEntity>();

	@Override
	public String getWarnType() {
		return Constants.VAL_BUS_STATUS_20;
	}

	@Override
	public void onHandler(BusInstance busInstance) throws BusPositionWarnHandlerException {
		logger.debug("【下一趟发车时刻预警提醒信息处理】");
		
		String seconds = PropertiesUtils.getString("system.parameter.trip.next.remind.second");
		int stationIndex = PropertiesUtils.getIntValue("system.parameter.trip.next.remind.seq", 0);
		
		if(seconds != null){
			checkByTime(busInstance);
		}else if(stationIndex != 0){
			checkBySeq(busInstance, stationIndex);
		}

	}

	private void checkByTime(BusInstance busInstance) {

		DeparterSchedule ds = null;
		if (busInstance.isInStandBy()) {
			// 在待发区，针对双向发车而言线路类型已经切换了
			ds = scheduleService.getDeparterSchedule(busInstance.getLineUuid(), busInstance.getLineType(), busInstance.getBusUuid(), busInstance.getTime(), 0, true);

		} else {
			ds = scheduleService.getDeparterSchedule(busInstance.getLineUuid(), null, busInstance.getBusUuid(), busInstance.getTime(), 0, true);
		}

		if (ds != null) {
			sendMessage(busInstance, ds);
		}
	}

	
	private void checkBySeq(BusInstance busInstance, int stationIndex) {

		boolean flag = false;
		DeparterSchedule ds = null;
		if (busInstance.isInStandBy()) {
			// 在待发区，针对双向发车而言线路类型已经切换了
			ds = scheduleService.getDeparterSchedule(busInstance.getLineUuid(), busInstance.getLineType(),
					busInstance.getBusUuid(), busInstance.getTime(), 0, true);
			flag = true;

		} else if (busInstance.isEnterOut()) {

			Integer lineBfType = busLineService.getLineBfType(busInstance.getLineUuid());// 获取发车类型（0单向
																							// ，1双向，2环线）
			String lineTypeOrg = busInstance.getStationLineTypeOrg();
			int currentStationSeq = Integer.parseInt(busInstance.getStationLineSeqOrg());

			int stationStart = Math.abs(stationIndex);

			if (lineBfType == 0) {
				if (lineTypeOrg.equals(Constants.VAL_LINE_DOWN)) {
					for (int i = stationStart; i > 0; i--) {
						flag = busLineService.isLineStationByIndex(busInstance.getLineUuid(), lineTypeOrg,
								currentStationSeq, -stationIndex);
						if (flag) {
							break;
						}
					}
				}
			} else if (lineBfType == 1 || lineBfType == 2) {
				for (int i = stationStart; i > 0; i--) {
					flag = busLineService.isLineStationByIndex(busInstance.getLineUuid(), lineTypeOrg,
							currentStationSeq, -stationIndex);
					if (flag) {
						break;
					}
				}
			}
			if (flag) {
				ds = scheduleService.getDeparterSchedule(busInstance.getLineUuid(), lineTypeOrg,
						busInstance.getBusUuid(), busInstance.getTime(), 0, true);
			}
		}

		if (flag) {
			/**
			 * 支持多次下发
			 */
			if (nextDepartureAlertMap.containsKey(busInstance.getBusUuid())) {
				sendMessage(busInstance, ds);
			}
		}
	}

	private void sendMessage(BusInstance busInstance, DeparterSchedule ds) {
		NextDepartureEntity entity = nextDepartureAlertMap.get(busInstance.getBusUuid());

		if (entity == null) {
			// 表示没有下发过,创建之
			entity = new NextDepartureEntity(ds.getBrsdUuid(), 0, new Date(), getSecondByTime());
		} else {
			// 如果不是同一趟次
			if (!entity.getBrsdUuid().equals(ds.getBrsdUuid())) {
				entity.setBrsdUuid(ds.getBrsdUuid());
				entity.setCount(0);
				entity.setTime(new Date());
				entity.setTimesByTime(getSecondByTime());	// 重置按照 提前多少站下发
			}
		}

		if(entity.getTimesByTime().size() > 0){
			// 提前 多少分钟 下发
			Long timeSecond = null;
			List<Long> timesByTime = entity.getTimesByTime();
			long secondInterval = DateUtils.secondInterval(ds.getDepartureTime(), busInstance.getTime());
			for (Long _secondInterval : timesByTime) {
				if(_secondInterval < secondInterval){
					timeSecond = _secondInterval;
					break;
				}
			}
			
			if(timeSecond != null){
				entity.getTimesByTime().remove(timeSecond);// 移除当前判定条件
				sendMessage(busInstance, ds, entity);
			}
			
		}else{
			// 提前多少站下发
			int maxtAlert = 1;// 最大提醒次数
			if (entity.getCount() < maxtAlert) {
				entity.setCount((entity.getCount() + 1));
				sendMessage(busInstance, ds, entity);
			}
		}
	}
	
	private void sendMessage(BusInstance busInstance, DeparterSchedule ds, NextDepartureEntity entity){
		logger.debug("【下一趟发车时刻预警】{}-{} 下一趟发车时刻预警提醒", busInstance.getDevCode(), busInstance.getBusNumber());
		String content = "下一趟发车时刻：" + DateUtils.formatDate(ds.getDepartureTime(), "HH:mm");
		sendPlatformMessageToTerminalService.sendDepartureTimeMessage(busInstance.getDevCode(), busInstance.getDevLineId(), content);
		nextDepartureAlertMap.put(busInstance.getBusUuid(), entity);
	}
	
	
	private List<Long> getSecondByTime(){
		String seconds = PropertiesUtils.getString("system.parameter.trip.next.remind.second", null); 		// 根据设置时间阀值提醒下一站发车时刻
		List<Long> timesList = null;
		if(seconds != null){
			String[] secondTimes = seconds.split(",");
			timesList = new ArrayList<Long>();
			for (String string : secondTimes) {
				timesList.add(Long.parseLong(string));
			}
		}
		return timesList;
	}

	@Override
	public void stopWarn(BusInstance busInstance) {
		// TODO Auto-generated method stub

	}

	class NextDepartureEntity {

		public NextDepartureEntity() {
		};

		public NextDepartureEntity(String brsdUuid, int count, Date time, List<Long> timesByTime) {
			this.brsdUuid = brsdUuid;
			this.count = count;
			this.time = time;
			if(timesByTime != null){
				this.timesByTime.addAll(timesByTime);
			}
		}

		// 当前发送时刻UUID
		private String brsdUuid;
		// 下发次数
		private int count;
		// 最后一次发送时间
		private Date time;
		// 按照时间 间隔下发
		private List<Long> timesByTime = new ArrayList<Long>();

		public String getBrsdUuid() {
			return brsdUuid;
		}

		public void setBrsdUuid(String brsdUuid) {
			this.brsdUuid = brsdUuid;
		}

		public int getCount() {
			return count;
		}

		public void setCount(int count) {
			this.count = count;
		}

		public Date getTime() {
			return time;
		}

		public void setTime(Date time) {
			this.time = time;
		}

		public List<Long> getTimesByTime() {
			return timesByTime;
		}

		public void setTimesByTime(List<Long> timesByTime) {
			this.timesByTime = timesByTime;
		}

	}

}
